package com.sky.server.impl;

import cn.hutool.core.bean.BeanUtil;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.exception.SqlException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.server.SetmealServer;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServerImpl implements SetmealServer {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    @Transactional
    public void addSetmeal(SetmealDTO setmealDTO) {
        // 添加套餐
        try {
            Setmeal setmeal = new Setmeal();
            BeanUtil.copyProperties(setmealDTO, setmeal);
            setmeal.setCreateTime(LocalDateTime.now());
            setmealMapper.save(setmeal);
            List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes().stream().map(s ->
                    {
                        SetmealDish setmealDish = new SetmealDish();
                        BeanUtil.copyProperties(s, setmealDish);
                        setmealDish.setSetmealId(setmeal.getId());
                        return setmealDish;
                    }
            ).collect(Collectors.toList());
            setmealDishMapper.addSetmealDish(setmealDishes);
        } catch (Exception e) {
            throw new SqlException("添加套餐");
        }
    }

    // 分页查询
    @Override
    public PageResult getPage(SetmealPageQueryDTO setmealPageQueryDTO) {
        List<Setmeal> setmealList = setmealMapper.getList(setmealPageQueryDTO);
        setmealList = setmealList.stream().skip((setmealPageQueryDTO.getPage() - 1) * setmealPageQueryDTO.getPageSize())
                .limit(setmealPageQueryDTO.getPageSize()).collect(Collectors.toList());
        List<SetmealVO> collect = setmealList.stream().map(setmeal -> {
            SetmealVO setmealVO = new SetmealVO();
            BeanUtil.copyProperties(setmeal, setmealVO);
            setmealVO.setCategoryName(categoryMapper.getBySetmealId(setmeal.getCategoryId()).getName());
            List<SetmealDish> bySetmealId = setmealDishMapper.getBySetmealId(setmeal.getId());
            setmealVO.setSetmealDishes(bySetmealId);
            return setmealVO;
        }).collect(Collectors.toList());

        PageResult pageResult = new PageResult();
        pageResult.setTotal(collect.size());
        pageResult.setRecords(collect);
        return pageResult;
    }

    @Override
    public SetmealVO getById(Long setmealId) {
        SetmealVO setmealVO = new SetmealVO();
        // 读套餐主表 setmeal
        Setmeal setmeal = setmealMapper.getById(setmealId);
        BeanUtils.copyProperties(setmeal, setmealVO);
        // 读套餐_菜品关系表 setmeal_dish
        List<SetmealDish> setmealDishes = setmealDishMapper.getBySetmealId(setmealId);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    @Override
    public List<Setmeal> getListBycategoryId(Long categoryId) {
        SetmealVO setmealVO = new SetmealVO();
        // 读套餐主表 setmeal
        List<Setmeal> list = setmealMapper.getListBycategoryId(categoryId);
        return list;
    }


    @Transactional
    public void deleteBatch(List<Long> ids) {
        ids.forEach(id -> {
            Setmeal setmeal = setmealMapper.getById(id);
            if (1 == setmeal.getStatus()) {
                // 起售中的套餐不能删除
                throw new BaseException("删除错误");
            }
        });

        ids.forEach(setmealId -> {
            // 删除套餐表中的数据
            setmealMapper.deleteById(setmealId);
            // 删除套餐菜品关系表中的数据
            setmealDishMapper.deleteBySetmealId(setmealId);
        });
    }

    // 根据id查询套餐和套餐菜品关系
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        Setmeal setmeal = setmealMapper.getBySetemealId(id);
        List<SetmealDish> bySetmealId = setmealDishMapper.getBySetmealId(setmeal.getId());
        SetmealVO setmealVO = new SetmealVO();
        BeanUtil.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(bySetmealId);
        return setmealVO;
    }


    // 修改套餐
    @Transactional
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        // 1、修改套餐表，执行update
        setmealMapper.update(setmeal);

        // 套餐id
        Long setmealId = setmealDTO.getId();

        // 2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        setmealDishMapper.deleteBySetmealId(setmealId);

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
        });
        // 3、重新插入套餐和菜品的关联关系，操作setmeal_dish表，执行insert
        setmealDishMapper.insertBatch(setmealDishes);
    }

    // 套餐起售、停售
    public void startOrStop(Integer status, Long id) {
        if (status == 0) {
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if (dishList != null && dishList.size() > 0) {
                dishList.forEach(dish -> {
                    if (1 == dish.getStatus()) {
                        throw new BaseException("无法修改撞");
                    }
                });
            }
        }
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(status);
        setmealMapper.update(setmeal);
    }

    /**
     * 条件查询
     *
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }

}
